﻿using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace DotNet.Common
{
	class XMLConfig<DataType>
		where DataType : new()
	{
		XmlSerializer m_ser;
		string m_filename;
		DataType m_data;

		public DataType Data { get { return m_data; } }

		public XMLConfig()
		{
			m_ser = new XmlSerializer(typeof(DataType));
		}

		public string FileName
		{
			get { return m_filename; }
		}

		public bool Load(string filename)
		{
			if (filename == null)
				return false;

			if (!File.Exists(filename))
			{
				m_filename = filename;
				m_data = new DataType();
				return false;
			}

			if (m_filename != null && string.Compare(m_filename, filename, true) != 0)
			{
				Save();
			}

			try
			{
				m_filename = filename;
				Stream file = new FileStream(m_filename, FileMode.Open, FileAccess.Read);
				m_data = (DataType)m_ser.Deserialize(file);
				file.Close();
				return true;
			}
			catch
			{
				m_data = new DataType();
				return false;
			}
		}

		public void Create(string filename)
		{
			if (string.Compare(m_filename, filename, true) != 0)
				Save();

			m_filename = filename;
			m_data = new DataType();
			Save();
		}

		public void Save()
		{
			try
			{
				if (!string.IsNullOrEmpty(m_filename))
				{
					Stream file = new FileStream(m_filename, FileMode.Create, FileAccess.Write);
					m_ser.Serialize(file, m_data);
					file.Close();
				}
			}
			catch
			{

			}
		}

		public void Unload()
		{
			Save();
			m_filename = string.Empty;
			m_data = new DataType();
		}
	}
}
